package org.farm.aliyunIot;

import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.apache.commons.codec.binary.Base64;
import org.farm.config.IotConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.net.URI;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@EnableAsync  // 启用异步处理
public class AmqpClient {

    @Autowired
    private IotConfig iotConfig;


    private static final Logger logger = LoggerFactory.getLogger(AmqpClient.class);

    private static final int connectionCount = 4;

    private final ExecutorService executorService= new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 2,
            60,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(50000)
    );

    public static void main(String[] args) {
        SpringApplication.run(AmqpClient.class, args);
    }


    public void start() throws Exception {
        List<Connection> connections = new ArrayList<>();

        for (int i = 0; i < connectionCount; i++) {
            long timeStamp = System.currentTimeMillis();
            String signMethod = "hmacsha1";

            String userName =  iotConfig.getClientId() + "-" + i + "|authMode=aksign"
                    + ",signMethod=" + signMethod
                    + ",timestamp=" + timeStamp
                    + ",authId=" + iotConfig.getAccessKey()
                    + ",iotInstanceId=" + iotConfig.getIotInstanceId()
                    + ",consumerGroupId=" + iotConfig.getConsumerGroupId()
                    + "|";

            String signContent = "authId=" + iotConfig.getAccessKey() + "&timestamp=" + timeStamp;
            String password = doSign(signContent, iotConfig.getAccessSecret(), signMethod);
            String connectionUrl = "failover:(amqps://" + iotConfig.getHost() + ":5671?amqp.idleTimeout=80000)"
                    + "?failover.reconnectDelay=30";

            Hashtable<String, String> hashtable = new Hashtable<>();
            hashtable.put("connectionfactory.SBCF", connectionUrl);
            hashtable.put("queue.QUEUE", "default");
            hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
            Context context = new InitialContext(hashtable);
            ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");
            Destination queue = (Destination) context.lookup("QUEUE");

            Connection connection = cf.createConnection(userName, password);
            connections.add(connection);

            ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener);

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            connection.start();

            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(messageListener);
        }

        logger.info("AMQP demo is started successfully, and will exit after 60s");

        Thread.sleep(60 * 1000);

        logger.info("Shutting down...");

        connections.forEach(c -> {
            try {
                c.close();
            } catch (JMSException e) {
                logger.error("Failed to close connection", e);
            }
        });

        executorService.shutdown();
        if (executorService.awaitTermination(10, TimeUnit.SECONDS)) {
            logger.info("Shutdown success");
        } else {
            logger.info("Failed to handle messages");
        }
    }


    private void processMessage(Message message) {
        try {
            byte[] body = message.getBody(byte[].class);
            String content = new String(body);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            long generateTime = message.getLongProperty("generateTime");
            logger.info("Received message: topic = {}, messageId = {}, generateTime = {}, content = {}",
                    topic, messageId, generateTime, content);
        } catch (Exception e) {
            logger.error("Error processing message", e);
        }
    }

    private MessageListener messageListener = new MessageListener() {
        @Override
        public void onMessage(final Message message) {
            try {
                // 异步处理消息
                executorService.submit(() -> {
                    processMessage(message);
                });
            } catch (Exception e) {
                logger.error("Error submitting task", e);
            }
        }
    };

    private static final JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            logger.info("Connection established, remoteUri: {}", remoteURI);
        }

        @Override
        public void onConnectionFailure(Throwable error) {
            logger.error("Connection failure: {}", error.getMessage());
        }

        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            logger.info("Connection interrupted, remoteUri: {}", remoteURI);
        }

        @Override
        public void onConnectionRestored(URI remoteURI) {
            logger.info("Connection restored, remoteUri: {}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {
            // no-op
        }

        @Override
        public void onSessionClosed(Session session, Throwable cause) {
            // no-op
        }

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {
            // no-op
        }

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {
            // no-op
        }
    };

    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }
}
